

// const TIM = require('../../../sdk/tim-wx-sdk/index');

let RECORD_CONST = require("record_status");
let RecordStatus = RECORD_CONST.RecordStatus;
let RecordDesc = RECORD_CONST.RecordDesc;
import { sendImMsgConfig } from "../../../service/config"
// imTODO
import { NEWIMAGE_URL } from "../../../service/base_service"
let RunAnimation = false
const InitHeight = [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50];
let app = getApp();
//that.sendImMsgConfig(textStr, that.data.chatData.chatUserId
Component({
	properties: {
		username: {
			type: String,
			value: '',
		},
		chatType: {
			type: String,

		},
	},
	data: {
		changedTouches: null,
		recordStatus: RecordStatus.HIDE,
		RecordStatus,
		RecordDesc,		// 模板中有引用
		radomheight: InitHeight,
		recorderManager: wx.getRecorderManager(),
		recordClicked: false
	},
	methods: {
		toggleWithoutAction(e) {
			// 阻止 tap 冒泡
		},

		toggleRecordModal() {
			this.setData({
				recordStatus: this.data.recordStatus == RecordStatus.HIDE ? RecordStatus.SHOW : RecordStatus.HIDE,
				radomheight: InitHeight,
			});
		},

		handleRecordingMove(e) {
			var touches = e.touches[0];
			var changedTouches = this.data.changedTouches;
			if (!changedTouches) {
				return;
			}

			if (this.data.recordStatus == RecordStatus.SWIPE) {
				if (changedTouches.pageY - touches.pageY < 20) {
					this.setData({
						recordStatus: RecordStatus.HOLD
					});
				}
			}
			if (this.data.recordStatus == RecordStatus.HOLD) {
				if (changedTouches.pageY - touches.pageY > 20) {
					this.setData({
						recordStatus: RecordStatus.SWIPE
					});
				}
			}
		},

		handleRecording(e) {
			let me = this;
			me.setData({
				recordClicked: true
			})
			setTimeout(() => {
				if (me.data.recordClicked == true) {
					executeRecord()
				}
			}, 350)
			function executeRecord() {
				wx.getSetting({
					success: (res) => {
						let recordAuth = res.authSetting['scope.record']
						if (recordAuth == false) { //已申请过授权，但是用户拒绝
							wx.openSetting({
								success: function (res) {
									let recordAuth = res.authSetting['scope.record']
									if (recordAuth == true) {
										wx.showToast({
											title: "授权成功",
											icon: "success"
										})
									} else {
										wx.showToast({
											title: "请授权录音",
											icon: "none"
										})
									}
									me.setData({
										isLongPress: false
									})
								}
							})
						} else if (recordAuth == true) { // 用户已经同意授权
							startRecord()
						} else { // 第一次进来，未发起授权
							wx.authorize({
								scope: 'scope.record',
								success: () => {//授权成功
									wx.showToast({
										title: "授权成功",
										icon: "success"
									})
								}
							})
						}
					},
					fail: function () {
						wx.showToast({
							title: "鉴权失败，请重试",
							icon: "none"
						})
					}
				})
			}

			function startRecord() {
				me.data.changedTouches = e.touches[0];
				me.setData({
					recordStatus: RecordStatus.HOLD
				});
				RunAnimation = true;
				me.myradom();

				let recorderManager = me.data.recorderManager || wx.getRecorderManager();
				recorderManager.onStart(() => {
					// console.log("开始录音...");
				});
				recorderManager.start({
					format: "mp3"
				});
				// 超时
				setTimeout(function () {
					me.handleRecordingCancel();
					RunAnimation = false
				}, 100000);
			}
		},

		handleRecordingCancel() {
			RunAnimation = false
			let recorderManager = this.data.recorderManager;
			// 向上滑动状态停止：取消录音发放
			if (this.data.recordStatus == RecordStatus.SWIPE) {
				this.setData({
					recordStatus: RecordStatus.RELEASE
				});
			}
			else {
				this.setData({
					recordStatus: RecordStatus.HIDE,
					recordClicked: false
				});
			}

			recorderManager.onStop((res) => {
				// console.log("结束录音...", res);
				if (this.data.recordStatus == RecordStatus.RELEASE) {
					console.log("user canceled");
					this.setData({
						recordStatus: RecordStatus.HIDE
					});
					return;
				}
				if (res.duration < 1000) {
					wx.showToast({
						title: "录音时间太短",
						icon: "none"
					})
				} else {
					// 上传
					this.uploadRecord(res);
				}
			});
			// 停止录音
			recorderManager.stop();
		},

		// isGroupChat(){
		// 	return this.data.chatType == msgType.chatType.CHAT_ROOM;
		// },

		// getSendToParam(){
		// 	return this.isGroupChat() ? this.data.username.groupId : this.data.username.your;
		// },

		uploadRecord(res) {
			console.log("JJLog:录音成功:" + JSON.stringify(res));
			// imTODO
			this.sendNewAudioMsg(res);
			return;
			const message = app.globalData.tim.createAudioMessage({
				to: this.properties.username,
				conversationType: this.properties.chatType,
				payload: {
					file: res
				}
			});

			// 5. 发送消息
			let that = this;
			let promise = app.globalData.tim.sendMessage(message);
			wx.showLoading({
				title: '发送中...',
			})
			promise.then(function (imResponse) {
				wx.hideLoading();
				// 发送成功
				console.log("JJLog:发送音频消息成功:" + JSON.stringify(imResponse));
				that.sendImMsgConfig("语音消息", that.properties.username);
				//回调音频消息:
				that.triggerEvent(
					"newAudioMsg",
					{
						msg: imResponse.data.message
					}
				);
			}).catch(function (imError) {
				wx.hideLoading();
				wx.showToast({
					title: '消息发送失败',
					icon: "none"
				})
				// 发送失败
				console.warn('JJLog发送音频消息失败===:', imError);
			});
			//回调音频消息出去:
			// me.triggerEvent(
			// 	"newAudioMsg",
			// 	{
			// 		msg: msg,
			// 		type: msgType.AUDIO,
			// 	},
			// 	{
			// 		bubbles: true,
			// 		composed: true
			// 	}
			// );
		},
		// imTODO 发送音频消息
		sendNewAudioMsg(res) {
			wx.showLoading({
				title: '消息发送中...',
			})
			let that = this;
			let url = "https://up-z2.qiniup.com"
			let filePath = res.tempFilePath
			let keyPref = "/tempIm"
			let expandName = filePath.substring(filePath.length - 10, filePath.length)
			let audioTime = Math.round(res.duration / 1000);
			wx.uploadFile({
				url: url,
				filePath: filePath,
				name: 'file',
				formData: {
					'token': wx.getStorageSync('qiniu_token'),
					'key': keyPref + "/" + new Date().getTime() + expandName,
				},
				header: {
					"Content-Type": "multipart/form-data"
				},
				success: function (res) {
					wx.hideLoading();
					let resultData = JSON.parse(res.data);
					resultData.complateUrl = NEWIMAGE_URL + resultData.key
					let time = new Date().getTime();
					let sendMsgData = {
						send: app.globalData.openId,
						receive: that.properties.username,
						info: {
							audioID: app.globalData.imAppId + time,
							payload: {
								text: "",
								url: resultData.complateUrl,
								second: audioTime
							}
						},
						msgType: "MSG_AUDIO",
						appId: app.globalData.imAppId,
						time: new Date().getTime(),
					}
					app.globalData.socketTask.send({
						data: JSON.stringify(sendMsgData),
						success: (res) => {
							console.log("JJLog:新IM发送音频消息成功=====")
							//回调音频消息 这里回调出去的msg不全，还得拼接一些参数
							that.triggerEvent(
								"newAudioMsg",
								{
									msg: sendMsgData
								}
							);
							that.sendImMsgConfig("语音消息", that.properties.username);
						},
						fail: (err => {
							wx.showToast({
								title: '消息发送失败',
								icon: "none"
							})
							console.error("JJLog:新IM发送音频消息失败:", err)
						})
					})
				},
				fail: function (err) {
					wx.hideLoading();
					console.error("JJLog:音频上传失败========:", err)
					wx.showToast({
						title: '消息发送失败',
						icon: "none"
					})
				}
			})
		},
		sendImMsgConfig(content, toOpenId) {
			let obj = {
				content,
				toOpenId,
			}
			sendImMsgConfig(obj).then(res => { })
		},

		myradom() {
			const that = this;
			var _radomheight = that.data.radomheight;
			for (var i = 0; i < that.data.radomheight.length; i++) {
				//+1是为了避免为0
				_radomheight[i] = (100 * Math.random().toFixed(2)) + 10;
			}
			that.setData({
				radomheight: _radomheight
			});
			if (RunAnimation) {
				setTimeout(function () { that.myradom(); }, 500);
			} else {
				return
			}
		}
	},

	// lifetimes
	created() { },
	attached() { },
	moved() { },
	detached() { },
	ready() { },
});
